package com.wxy.netty;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.util.concurrent.ExecutionException;

/**
 * @author 47868
 */
public class PromiseTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        EventLoop loop = new NioEventLoopGroup().next();
        DefaultPromise<Integer> promise = new DefaultPromise<>(loop);
        loop.submit(()->{
            try {
                System.out.println(Thread.currentThread().getName() + " 正在计算...");
                Thread.sleep(1000);
                promise.setSuccess(100);
            } catch (Exception e) {
                e.printStackTrace();
                promise.setFailure(e);
            }
        });

//        System.out.println(Thread.currentThread().getName() + "等待结果");
//        System.out.println(promise.get());
        promise.addListener(new GenericFutureListener<Future<? super Integer>>() {

            @Override
            public void operationComplete(Future<? super Integer> future) throws Exception {
                System.out.println(Thread.currentThread().getName()+" "+promise.get());
                loop.shutdownGracefully();
            }
        });
    }
}
